package cn.wmingming.e3mall.cart.controller;

import cn.wmingming.common.pojo.E3Result;
import cn.wmingming.common.utils.CookieUtils;
import cn.wmingming.common.utils.JsonUtils;
import cn.wmingming.e3mall.cart.service.CartService;
import cn.wmingming.e3mall.manager.service.ItemService;
import cn.wmingming.e3mall.pojo.TbItem;
import cn.wmingming.e3mall.pojo.TbUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
public class CartController {

    @Autowired
    private ItemService itemService;
    @Autowired
    private CartService cartService;
    @Value("${COOKIES_CART}")
    private String COOKIES_CART;


    @RequestMapping("/cart/add/{productId}")
    public String cartAdd(@PathVariable Long productId, @RequestParam(defaultValue = "1") Integer num, HttpServletRequest request, HttpServletResponse response){
        //判断用户是否登录
        TbUser user = (TbUser) request.getAttribute("user");
        if(user != null){
            //已经登录时,将调用cartService服务添加商品到购物车
            cartService.addCart(productId,user.getId().toString(),num);
            //返回逻辑视图
            return "cartSuccess";
        }

        //未登录时
        //1 从cookies中获取购物车列表
        List<TbItem> tbItemList = getCartFormCookies(request);
        //2 判断商品在商品列表中是否存在
        boolean hasItem = false;
       for (TbItem item:tbItemList){
           if(item.getId() == productId.longValue()){
               //3 商品已经在购车车中，数量增加
               item.setNum(item.getNum()+num);
               hasItem = true;
           }
           break;
       }
       //4 商品不在购物车中，往购物车列表中添加商品
       if(!hasItem){
           TbItem item = itemService.getItemById(productId);
           //设置数量
           item.setNum(num);
           //取一张图片
           String image = item.getImage();
           if(StringUtils.isNoneBlank(image)){
               String[] split = image.split(",");
               item.setImage(split[0]);
           }
           //5 添加到购物车列表
           tbItemList.add(item);
       }
       //6 添加到cookies缓存中
        CookieUtils.setCookie(request, response, COOKIES_CART, JsonUtils.objectToJson(tbItemList), true);

        return "cartSuccess";
    }


    @RequestMapping("/cart/cart")
    public String showCartList(Model model,HttpServletRequest request,HttpServletResponse response){
        //1 从cookie中取商品列表。
        List<TbItem> cartList = getCartFormCookies(request);
        //2 判断用户是否登录
        TbUser user = (TbUser) request.getAttribute("user");
        if(user != null){
            //3 已经登录，将cookies的购物车与服务端的购物车进行合并
            cartService.mergeCart(user.getId().toString(),cartList);
            //4 将cookies购物车删除
            CookieUtils.deleteCookie(request,response,COOKIES_CART);
            //5 从服务端获取购物列表
            cartList = cartService.getCartList(user.getId().toString());
        }
        //6 没有登录
        //把商品列表传递给页面。
        model.addAttribute("cartList",cartList);
        return "cart";
    }


    @RequestMapping("/cart/update/num/{itemid}/{num}")
    @ResponseBody
    public E3Result cartUpdateNum(@PathVariable Long itemid, @PathVariable Integer num, HttpServletRequest request, HttpServletResponse response){

        //1 判断用户是否登录
        TbUser user = (TbUser) request.getAttribute("user");
        if(user != null){
            //2 已经登录,调用cartService更新购物车商品数量
            cartService.cartUpdateNum(user.getId().toString(),itemid.longValue(),num);
        }

        //3 没有登录，写入本地cookies
        //从cookie中取商品列表
        List<TbItem> itemList = getCartFormCookies(request);
        for(TbItem item:itemList){
            //遍历商品列表找到对应商品
            if(item.getId() == itemid.longValue()){
                //更新商品数量
                item.setNum(num);
                break;
            }
        }
        //把商品列表写入cookie
        CookieUtils.setCookie(request,response,COOKIES_CART,JsonUtils.objectToJson(itemList),true);
        //响应e3Result。Json数据
        return E3Result.ok();
    }

    @RequestMapping("/cart/delete/{itemId}")
    public String deleteCartItem(@PathVariable Long itemId, HttpServletRequest request, HttpServletResponse response){
        //1 判断用户是否登录
        TbUser user = (TbUser) request.getAttribute("user");
        if(user != null){
            //2 调用cartService从购物车列表中删除商品
            cartService.deleteCartItem(user.getId().toString(),itemId);
        }else {
            //从cookies从获得购物车列表
            List<TbItem> itemList = getCartFormCookies(request);
            for (TbItem item:itemList){
                //找到要删除的商品，从购物车列表中删除
                if(item.getId() == itemId.longValue()){
                    itemList.remove(item);
                    break;
                }
            }
            //写回cookies
            CookieUtils.setCookie(request,response,COOKIES_CART,JsonUtils.objectToJson(itemList),true);
        }
        return "redirect:/cart/cart.html";
    }


    private List<TbItem> getCartFormCookies(HttpServletRequest request){
        //取购物车列表
        String cookieValue = CookieUtils.getCookieValue(request, COOKIES_CART,true);
        //判断cookieValue是否为null
        if(StringUtils.isNoneBlank(cookieValue)){
            //将json转换为list
            List<TbItem> tbItemList = JsonUtils.jsonToList(cookieValue, TbItem.class);
            return tbItemList;
        }
        return new ArrayList<>();
    }
}
